package com.power.using.mybomb;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.orhanobut.logger.Logger;
import com.power.using.mybomb.base.BaseActivity;
import com.power.using.mybomb.bean.User;
import com.power.using.mybomb.db.NewFriendManager;
import com.power.using.mybomb.event.RefreshEvent;
import com.power.using.mybomb.ui.fragment.ContractFragment;
import com.power.using.mybomb.ui.fragment.ConversationFragment;
import com.power.using.mybomb.ui.fragment.SetFragment;
import com.power.using.mybomb.util.IMMLeaks;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.ConnectStatusChangeListener;
import cn.bmob.newim.notification.BmobNotificationManager;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;

public class MainActivity extends BaseActivity {

    @BindView(R.id.btn_conversation)
    TextView btn_conversation;
    @BindView(R.id.btn_set)
    TextView btn_set;
    @BindView(R.id.btn_contact)
    TextView btn_contact;

    @BindView(R.id.iv_conversation_tips)
    ImageView iv_conversation_tips;
    @BindView(R.id.iv_contact_tips)
    ImageView iv_contact_tips;
    private TextView[] mTabs;
    private ConversationFragment conversationFragment;
    private SetFragment setFragment;
    private ContractFragment contractFragment;
    private Fragment[] fragments;
    private int index;
    private int currentTabIndex;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        User user = BmobUser.getCurrentUser(User.class);
        //TODO 连接：3.1、登录成功、注册成功或处于登录状态重新打开应用后执行连接IM服务器的操作
        //判断用户是否登录，并且连接状态不是已连接，则进行连接操作
        if(!TextUtils.isEmpty(user.getObjectId())
            && BmobIM.getInstance().getCurrentStatus().getCode()!= ConnectionStatus.CONNECTED.getCode()){

            BmobIM.connect(user.getObjectId(), new ConnectListener() {
                @Override
                public void done(String s, BmobException e) {
                    if(e==null){
                        //服务器连接成功就发送一个更新事件，同步更新会话及主页的小红点
                        //TODO 会话：2.7、更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
                        BmobIM.getInstance()
                                .updateUserInfo(new BmobIMUserInfo(user.getObjectId(),user.getUsername(),user.getAvatar()));
                        EventBus.getDefault().post(new RefreshEvent());

                    }else{
                        toast(e.getMessage());
                    }
                }
            });

            //TODO 连接：3.3、监听连接状态，可通过BmobIM.getInstance().getCurrentStatus()来获取当前的长连接状态
            BmobIM.getInstance().setOnConnectStatusChangeListener(new ConnectStatusChangeListener() {
                @Override
                public void onChange(ConnectionStatus status) {
                    toast(status.getMsg());
                    Logger.i(BmobIM.getInstance().getCurrentStatus().getMsg());
                }
            });


        }

        IMMLeaks.fixFocusedViewLeak(getApplication());
        checkStoragePermissions(0);

    }

    /**
     * 兼容android6.0运行时权限
     * @param requestCode
     */
    private void checkStoragePermissions(int requestCode) {
        List<String> permissions = new ArrayList<>();
        int permissionCheckWrite = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheckWrite != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        int permissionCheckRead = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionCheckRead != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (permissions.size() > 0) {
            String[] missions = new String[]{};
            ActivityCompat.requestPermissions(this, permissions.toArray(missions), requestCode);
        } else {

        }
    }

    /**
     * TODO 1、兼容android6.0运行时权限
     * <p>
     * 权限授权结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void initView() {
        super.initView();
        mTabs = new TextView[3];
        mTabs[0]=btn_conversation;
        mTabs[1]=btn_contact;
        mTabs[2]=btn_set;
        mTabs[0].setSelected(true);
        initTab();



    }

    private void initTab() {
        conversationFragment = new ConversationFragment();
        setFragment = new SetFragment();
        contractFragment = new ContractFragment();
        fragments = new Fragment[]{conversationFragment,contractFragment,setFragment};
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container,conversationFragment)
                .add(R.id.fragment_container,contractFragment)
                .add(R.id.fragment_container,setFragment)
                .hide(contractFragment)
                .hide(setFragment)
                .show(conversationFragment)
                .commit();
    }

    public void onTabSelect(View view) {

        switch(view.getId()){
            case R.id.btn_conversation:
                index = 0;
                break;
            case R.id.btn_contact:
                index=1;
                break;
            case R.id.btn_set:
                index=2;
                break;

            default:

                break;
        }
        onTabIndex(index);
    }

    private void onTabIndex(int index) {

        if(currentTabIndex!=index){
            FragmentTransaction trx =
                    getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if(!fragments[index].isAdded()){
                trx.add(R.id.fragment_container,fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        mTabs[index].setSelected(true);
        currentTabIndex=index;


    }

    @Override
    protected void onResume() {
        super.onResume();
        checkRedPoint();

        BmobNotificationManager.getInstance(this).cancelNotification();
    }

    /**
     * 通知有在线消息接受
     * @param event
     */
    @Subscribe
    public void onEventMainThread(MessageEvent event){
        checkRedPoint();
    }

    /**
     * 通知有离线消息接受
     * @param event
     */
    @Subscribe
    public void onEventMianThread(OfflineMessageEvent event){
        checkRedPoint();
    }

    @Subscribe
    public void onEventMainThread(RefreshEvent event){
        checkRedPoint();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Logger.i("CheckLifeCycle","MainActivity is destoryed");
        BmobIM.getInstance().clear();
    }

    private void checkRedPoint() {

        int count= (int) BmobIM.getInstance().getAllUnReadCount();

        if(count>0){
            iv_conversation_tips.setVisibility(View.VISIBLE);
        }else{
            iv_conversation_tips.setVisibility(View.GONE);
        }

        if(NewFriendManager.getInstance(this).hasNewFriendInvitation()){
            iv_contact_tips.setVisibility(View.VISIBLE);
        }else{
            iv_contact_tips.setVisibility(View.GONE);
        }

    }
}
